﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Security.Permissions;
using System.Diagnostics;
using System.Threading;

namespace IMT
{
    /// <summary>
    /// Author: Elliott Perry 01/09/2011
    /// 
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //notify log of application start
            lstLog.Items.Add("Application Started At " + getTimeStamp());
           
            //Set Root Path Dialog
            txtxRootPath.Text = GlobalData.rootPath.ToString();

            //Make the "butFileWatchStop inactive
            butFileWatchStop.IsEnabled = false;


        }

        /// <summary>
        /// This method returns the current time in a timestamp so that it can be used for in file names and log files.
        /// </summary>
        /// <returns></returns>
        public string getTimeStamp()
        {

            string timeStamp = DateTime.Now.ToString("yyyy MM dd hh mm ss");

            return timeStamp;

        }


        /// <summary>
        /// This button is used to update the root path once the application begins
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butUpdateRootPath_Click(object sender, RoutedEventArgs e)
        {
            //change data
            GlobalData.rootPath = txtxRootPath.Text;

            //notify log
            lstLog.Items.Add("Root path changed to " + txtxRootPath.Text + " at " + getTimeStamp());

            
        }

        /// <summary>
        /// This creates an XML from in-system data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butCreateTestEvent_Click(object sender, RoutedEventArgs e)
        {

            string[,] UnderwriterArray = new string[3, 13];
            UnderwriterArray[0, 0] = "Lloyd's Syndicate 1919";
            UnderwriterArray[0, 1] = "John Smith";
            UnderwriterArray[0, 2] = "John.Smith@carrier1.com";
            UnderwriterArray[0, 3] = "duns"; // agency attribute
            UnderwriterArray[0, 4] = "1111111112";
            UnderwriterArray[0, 5] = "lloyds";// agency attribute
            UnderwriterArray[0, 6] = "8001";
            UnderwriterArray[0, 7] = "123456789";
            UnderwriterArray[0, 8] = "1";
            UnderwriterArray[0, 9] = "leader";
            UnderwriterArray[0, 10] = "acord";
            UnderwriterArray[0, 11] = "no";
            UnderwriterArray[0, 12] = "1";

            UnderwriterArray[1, 0] = "Lloyd's Syndicate 2007";
            UnderwriterArray[1, 1] = "John Smith";
            UnderwriterArray[1, 2] = "John.Smith@carrier2.com";
            UnderwriterArray[1, 3] = "duns"; // agency attribute
            UnderwriterArray[1, 4] = "222222222";
            UnderwriterArray[1, 5] = "lloyds";// agency attribute
            UnderwriterArray[1, 6] = "8002";
            UnderwriterArray[1, 7] = "123456789";
            UnderwriterArray[1, 8] = "2";
            UnderwriterArray[1, 9] = "otheragreementparty";
            UnderwriterArray[1, 10] = "email";
            UnderwriterArray[1, 11] = "no";
            UnderwriterArray[1, 12] = "2";


            UnderwriterArray[2, 0] = "Lloyd's Syndicate 2007";
            UnderwriterArray[2, 1] = "John Smith";
            UnderwriterArray[2, 2] = "John.Smith@carrier2.com";
            UnderwriterArray[2, 3] = "duns"; // agency attribute
            UnderwriterArray[2, 4] = "222222222";
            UnderwriterArray[2, 5] = "lloyds";// agency attribute
            UnderwriterArray[2, 6] = "8002";
            UnderwriterArray[2, 7] = "123456789";
            UnderwriterArray[2, 8] = "2";
            UnderwriterArray[2, 9] = "otheragreementparty";
            UnderwriterArray[2, 10] = "email";
            UnderwriterArray[2, 11] = "no";
            UnderwriterArray[2, 12] = "2";

            string[] DocumentArray = new string[1];
            DocumentArray[0] = @"C:\Users\Plationo\Documents\IMT\sample.doc";

            IMT.SubmitEndorsementMSG foo = new IMT.SubmitEndorsementMSG(
                        "CLIENTNAME",
                        "E04F....",
                        "SubmitEndorsement",
                        "Trisys Test",
                        "B5555",
                        "Alex Mattelaer",
                        "0771 540 6894",
                        "atest@bob.com",
                        "Unknown",
                        "B0901LH99999999",
                        "Test Endorsement - to TEST Env",
                        "reinsurance",
                        "cargo_unspecified",
                        "lineslip",
                        "End 001",
                        "Simple Test",
                        "no",
                        "1",
                        UnderwriterArray
                //DocumentArray
                        );

            

        }



        private void butFileWatchStart_Click(object sender, RoutedEventArgs e)
        {
            //Swap Enabled Buttons
            butFileWatchStart.IsEnabled = false;
            butFileWatchStop.IsEnabled = true;

            lstLog.Items.Add("File Watching Started on "+GlobalData.InputPath+ " at " + getTimeStamp());

            startFileWatcher();

            
        }

        /// <summary>
        /// Slightly BROKEN
        /// 
        /// This needs to be threaded to update the GUIlstBox
        /// </summary>
        [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
        private void startFileWatcher()
        {
            //File Watcher Code
            FileSystemWatcher watcher = new FileSystemWatcher();

            watcher.Path = GlobalData.InputPath;

            watcher.Filter = "*.*";

            watcher.NotifyFilter = NotifyFilters.LastAccess |
                                   NotifyFilters.LastWrite |
                                   NotifyFilters.FileName |
                                   NotifyFilters.DirectoryName;

            watcher.IncludeSubdirectories = false;

            watcher.Created += new FileSystemEventHandler(OnChanged);

            watcher.EnableRaisingEvents = true;

        }

        void OnChanged(object sender, FileSystemEventArgs e)
        {
            try
            {

                StringBuilder inputString = new System.Text.StringBuilder();

                //These commands will not work as the update should be threaded in WPF
                //lstLog.Items.Add("Object Added at " + getTimeStamp());
                //MessageBox.Show("Object Added");

                Debug.WriteLine("DEBUG: New Item Found in Folder File Name = " + e.FullPath);

                //Open the file and read in the first word. Pass this to a case statement and create associated objects.
                string path = e.FullPath;

                try
                {
                    using (StreamReader reader = new StreamReader(path))
                    {

                        while (reader.Peek() != GlobalData.MessageDelimiterASCII)
                        {
                            inputString.Append(char.ConvertFromUtf32(reader.Read()));
                        }

                        switch (inputString.ToString())
                        {
                            case "SUBMITENDORSEMENT":
                                Debug.WriteLine("DEBUG: SubmitEndorsement Message Found");
                                SubmitEndorsementMSG Message = new SubmitEndorsementMSG(path);
                                break;

                            default:
                                Debug.WriteLine("DEBUG: Message Type Not Found");
                                break;
                        }
                        
                    }
                }
                catch (Exception f)
                {

                    Debug.WriteLine("ERROR: Read Failed : " + f);
                }
                
            }
            catch (Exception f)
            {
                Debug.WriteLine("ERROR:" + f);
            }

        }

        private void butFileWatchStop_Click(object sender, RoutedEventArgs e)
        {
            //Swap enabled buttons
            butFileWatchStop.IsEnabled = false;
            butFileWatchStart.IsEnabled = true;

            lstLog.Items.Add("File Watching Stopped on " + GlobalData.InputPath + " at " + getTimeStamp());
        }



    }
}
